package com.yuanxin.app.appjob.controller.pc;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Random;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;

import org.springframework.stereotype.Controller;

import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.yuanxin.app.appjob.appobject.AssignmentAO;
import com.yuanxin.app.appjob.appobject.WorkingTableAO;
import com.yuanxin.app.appjob.appobject.PersonInfoAO;
import com.yuanxin.app.appjob.appobject.WorkingDetailAO;
import com.yuanxin.app.appjob.appobject.WorkingProgressAO;
import com.yuanxin.app.appjob.common.MVCViewName;
import com.yuanxin.app.appjob.entity.gen.WorkingTableCriteria;
import com.yuanxin.app.appjob.entity.gen.AssignmentCriteria;
import com.yuanxin.app.appjob.entity.gen.PersonInfoCriteria;
import com.yuanxin.app.appjob.entity.gen.WorkingDetailCriteria;
import com.yuanxin.app.appjob.entity.gen.WorkingProgressCriteria;
import com.yuanxin.app.appjob.service.IAssignment;
import com.yuanxin.app.appjob.service.IWorkingTable;
import com.yuanxin.app.appjob.service.IPersonInfo;
import com.yuanxin.app.appjob.service.IWorkingDetail;
import com.yuanxin.app.appjob.service.IWorkingProgressService;
import com.yuanxin.framework.logging.Logger;
import com.yuanxin.framework.logging.LoggerFactory;
import com.yuanxin.framework.service.ServiceResult;
import com.yuanxin.framework.util.DateTimeUtils;

@Controller
@RequestMapping(value = "/pc/workingtable")
public class WorkingTableController {
	
	@Resource
	IWorkingTable workingtableService;
	
	@Resource
	IAssignment assignmentService;
	
	@Resource
	IPersonInfo personInfoService;
	
	@Resource
	IWorkingDetail workingDetailService;
	
	@Resource
	IWorkingProgressService workingProgressService;
	
	private static Logger LOG = LoggerFactory.getLogger(WorkingTableController.class);
	@RequestMapping(value = "", method = { RequestMethod.GET, RequestMethod.POST })
	
	 public ModelAndView getHello(Model model, HttpServletRequest request) {
        LOG.info("有访问来自，IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
        LOG.info("SessionId %s", request.getSession().getId());
        //将当前时间传到前端
        model.addAttribute("currentTime", DateTimeUtils.formateDateToStr(new Date(),DateTimeUtils.FORMAT_YMD_HMS));
		//将当前运用名称传到前端
        model.addAttribute("currentUser",request.getSession());//把用户信息传到前端
        ModelAndView mv = new ModelAndView();
        mv.addObject(model);
        
        return mv;
    }
	  @RequestMapping(value = "/add", method = { RequestMethod.GET, RequestMethod.POST })
	    public String add(Model model, HttpServletRequest request) {
	        LOG.info("有访问来自，IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
	        LOG.info("SessionId %s", request.getSession().getId());
	        //将当前时间传到前端
	        model.addAttribute("currentTime", DateTimeUtils.formateDateToStr(new Date(),DateTimeUtils.FORMAT_YMD_HMS));
			//将当前运用名称传到前端
	       
	        model.addAttribute("currentUser",request.getSession());//把用户信息传到前端
	        PersonInfoAO pf = (PersonInfoAO)request.getSession().getAttribute("currentUser");
	        PersonInfoCriteria pc = new PersonInfoCriteria();
	        pc.createCriteria().andIdEqualTo(pf.getId());
	        ServiceResult<List<PersonInfoAO>> plist = personInfoService.selectByCriteria(pc);
	        PersonInfoAO upf = plist.getData().get(0);//取出用户信息
	        
	        AssignmentAO aa = new  AssignmentAO();
	        ModelAndView mv = new ModelAndView();
	        mv.addObject(model);
	        WorkingTableAO fsa = new WorkingTableAO();
	        fsa.setStatusDel("0");
	        fsa.setCreater(upf.getStaffName());
	        workingtableService.saveOrUpdate(fsa);
	        aa.setJobId(fsa.getId());
	        aa.setPersonId(upf.getId());
	        aa.setIsLeader("1");
	        assignmentService.saveOrUpdate(aa);
	        
	       
	        return "redirect:/pc/workingtable/showform/" + fsa.getId();
	        
	        
	    }  
	  
	
	    
	
	  @RequestMapping(value = "/list", method = { RequestMethod.GET, RequestMethod.POST })
	    public ModelAndView list(Model model, HttpServletRequest request) {
	        LOG.info("有访问来自，IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
	        LOG.info("SessionId %s", request.getSession().getId());
	        //将当前时间传到前端
	        model.addAttribute("currentTime", DateTimeUtils.formateDateToStr(new Date(),DateTimeUtils.FORMAT_YMD_HMS));
			//将当前运用名称传到前端
	        model.addAttribute("currentUser",request.getSession());//把用户信息传到前端
	        PersonInfoAO pf = (PersonInfoAO)request.getSession().getAttribute("currentUser");
	        PersonInfoCriteria pc = new PersonInfoCriteria();
	        pc.createCriteria().andIdEqualTo(pf.getId());
	        ServiceResult<List<PersonInfoAO>> plist = personInfoService.selectByCriteria(pc);
	        PersonInfoAO upf = plist.getData().get(0);//取出用户信息
	        
	        List<Long> joblist = new ArrayList<Long>();
	        WorkingDetailCriteria cc =new  WorkingDetailCriteria();
	        AssignmentCriteria ac = new  AssignmentCriteria();
	        ac.createCriteria().andPersonIdEqualTo(upf.getId());
	        ServiceResult<List<AssignmentAO>> alist =  assignmentService.selectByCriteria(ac);//取出Assignment与personid相同的信息
	        int datasize =alist.getData().size();
	        for(int i=0;i<datasize;i++){
	        	AssignmentAO aa = alist.getData().get(i);
	        	long b = Long.parseLong(aa.getJobId());
	        	joblist.add(b);
	         }
	        if(joblist.size() == 0){//关于joblist为空时的判断
	        	model.addAttribute("datalist", new ArrayList());
	        	
	        }else{
	        	cc.createCriteria().andJobIdIn(joblist);   
	 	           ServiceResult<List< WorkingDetailAO>> list =  workingDetailService.selectByCriteria(cc);
	 	        if(list!=null&& list.getData()!=null&& list.getData().size()>0){
		        	model.addAttribute("datalist", list.getData());
		        }else{
		        	model.addAttribute("datalist", new ArrayList());
		        }
		       
	        }
	        
	        ModelAndView mv = new ModelAndView();
	        mv.addObject(model);
	        mv.setViewName(MVCViewName.APP_APPJOB_PC_WORKINGDETAIL_WORKINGDETAILLIST.toString());
	        return mv;
	        
	     }
	    
	
	 
	 @RequestMapping(value = "/showform/{id}", method = { RequestMethod.GET, RequestMethod.POST })
	    public ModelAndView showform(@PathVariable String id , Model model, HttpServletRequest request) {
	    	LOG.info("有访问来自，IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
	    	LOG.info("SessionId %s", request.getSession().getId());
	    	//将当前时间传到前端
	    	model.addAttribute("currentTime", DateTimeUtils.formateDateToStr(new Date(),DateTimeUtils.FORMAT_YMD_HMS));
	    	//将当前运用名称传到前端
	    	 model.addAttribute("currentUser",request.getSession());//把用户信息传到前端
	    	 
	    	ServiceResult<WorkingTableAO> dataAO =  workingtableService.getById(id); 
	    	model.addAttribute("dataAO", dataAO.getData()); 
	    	
	    	PersonInfoCriteria cc = new PersonInfoCriteria();
	    	ServiceResult<List<PersonInfoAO>> pdataAO =  personInfoService.selectByCriteria(cc);
	    	model.addAttribute("persondata", pdataAO.getData());
	    	
	    	ModelAndView mv = new ModelAndView();
	    	mv.addObject(model);
	    	mv.setViewName(MVCViewName.APP_APPJOB_PC_WORKINGTABLE_WORKINGTABLEFORM.toString());
	    	return mv;
	    }  
	    
	 
	 @RequestMapping(value = "/view/{dataId}", method = { RequestMethod.GET, RequestMethod.POST })
	    public ModelAndView viewById(@PathVariable String dataId,Model model, HttpServletRequest request) {
	        LOG.info("有访问来自，IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
	        LOG.info("SessionId %s", request.getSession().getId());
	        //将当前时间传到前端
	        model.addAttribute("currentTime", DateTimeUtils.formateDateToStr(new Date(),DateTimeUtils.FORMAT_YMD_HMS));
			//将当前运用名称传到前端
	 	
	        model.addAttribute("currentUser",request.getSession());//把用户信息传到前端
	        
	        ModelAndView mv = new ModelAndView();
	        mv.addObject(model);
	        
	        return mv;
	    }
	    
	    
	    @RequestMapping(value = "/update/{dataId}", method = { RequestMethod.GET, RequestMethod.POST })
	    public ModelAndView updateById(@PathVariable String dataId,Model model, HttpServletRequest request) {
	        LOG.info("有访问来自，IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
	        LOG.info("SessionId %s", request.getSession().getId());
	        //将当前时间传到前端
	        model.addAttribute("currentTime", DateTimeUtils.formateDateToStr(new Date(),DateTimeUtils.FORMAT_YMD_HMS));
			//将当前运用名称传到前端
	 	
	        ModelAndView mv = new ModelAndView();
	        mv.addObject(model);
	        
	        return mv;
	    }
	    
	    @RequestMapping(value = "/delete/{dataId}", method = { RequestMethod.GET, RequestMethod.POST })
	    @ResponseBody
	    public Object deleteById(@PathVariable String dataId, HttpServletRequest request) {
	        LOG.info("有访问来自，IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
	        LOG.info("SessionId %s", request.getSession().getId());
	        //将当前时间传到前端
			//将当前运用名称传到前端
	       
	        ServiceResult<String> result = new ServiceResult<String>();
	        boolean flag = false;
	        try {
	        	WorkingTableAO aa = new WorkingTableAO();
	        	aa.setId(dataId);
	        	aa.setStatusDel("1");
	        	workingtableService.saveOrUpdate(aa);
	        	result.setSucceed(flag);
	 			result.setMsg("删除成功！");
	        } catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				result.setSucceed(flag);
				result.setMsg("删除失败！");
			}
	        return result;
	    }
	    
	    /**
	    *异步提交表单
	    **/
	    @RequestMapping(value = "/submitAJAXForm", method = { RequestMethod.GET, RequestMethod.POST })
	    @ResponseBody
	    public Object submitAJAXForm(@Valid WorkingTableAO source,Model model, HttpServletRequest request) {
	        LOG.info("有访问来自，IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
	        LOG.info("SessionId %s", request.getSession().getId());
	        //将当前时间传到前端
	        model.addAttribute("currentUser",request.getSession());//把用户信息传到前端
	        model.addAttribute("currentTime", DateTimeUtils.formateDateToStr(new Date(),DateTimeUtils.FORMAT_YMD_HMS));
			ServiceResult<Object> ret = new ServiceResult<Object>();

	        return ret;
	    }

		   @RequestMapping(value = "/submitForm", method = { RequestMethod.GET, RequestMethod.POST })
		   public String submitForm(@Valid WorkingTableAO source,Model model, HttpServletRequest request) {
		   	LOG.info(" з      ԣ IP: %s USER-AGENT: %s", request.getRemoteAddr(), request.getHeader("user-agent"));
		   	LOG.info("SessionId %s", request.getSession().getId());
		   	//
		   	model.addAttribute("currentTime", DateTimeUtils.formateDateToStr(new Date(),DateTimeUtils.FORMAT_YMD_HMS));
		    model.addAttribute("currentUser",request.getSession());//把用户信息传到前端
		    
		   	//保存工作信息
		    workingtableService.saveOrUpdate(source);
		    
		    //获取人员id
		    String str = source.getRemark();  
		    String[] strArray = null;   
	        strArray = str.split(",");
	        
	        //保存工作分配信息
	        String workid=source.getId();
	        for(int i=0; i<strArray.length; i++){ 
	             AssignmentAO as = new AssignmentAO();
	               as.setJobId(workid);
	               as.setIsLeader("0");
	               as.setPersonId(strArray[i]);
	               AssignmentCriteria ac = new AssignmentCriteria();
	               ac.createCriteria().andJobIdEqualTo(workid).andPersonIdEqualTo(strArray[i]);
	  		       ServiceResult<List< AssignmentAO>> list =  assignmentService.selectByCriteria(ac);
	  		     if(list!=null&& list.getData()!=null&& list.getData().size()>0){
	 
	            }else{
	            	    assignmentService.saveOrUpdate(as);
	            }
	        }
	        
	       
	       
	        //自动添加至反馈单（发起反馈之后）
	          
	        Date date = new Date();
	        String year =String.format("%tY",date);
	        
	        Calendar cl = Calendar.getInstance();
	    	cl.setFirstDayOfWeek(Calendar.SUNDAY); 
	        int week = cl.get(Calendar.WEEK_OF_YEAR); //获取周数
	    	int d = 0;
	        if (cl.get(Calendar.DAY_OF_WEEK) == 1) {
	            d = -6;
	        } else {
	            d = 2 - cl.get(Calendar.DAY_OF_WEEK);
	        }
	    	int dayOfWeek = cl.get(Calendar.DAY_OF_WEEK);
	    	cl.add(Calendar.DAY_OF_WEEK, d);
	    	String weekstart = new SimpleDateFormat("yyyy-MM-dd").format(cl.getTime());//本周开始
	        cl.add(Calendar.DAY_OF_WEEK, 6);
	        String weekend = new SimpleDateFormat("yyyy-MM-dd").format(cl.getTime());//本周结束
	        cl.add(Calendar.DAY_OF_WEEK, 5);
	        String nextFriday = new SimpleDateFormat("yyyy-MM-dd").format(cl.getTime());//下周五
	        
	        WorkingProgressCriteria progcc=new WorkingProgressCriteria();
	        WorkingProgressAO wac = new  WorkingProgressAO();
	        progcc.createCriteria().andWeekNumEqualTo(Integer.toString(week));
	        ServiceResult<List<WorkingProgressAO>> proglist = workingProgressService.selectByCriteria(progcc);
	        int a = 1;
	        int b = 0;
	        if(proglist.getData().size()>0){
	        	
	        	for(int i=0;i<proglist.getData().size();i++){
	        		if(Long.parseLong(workid) == proglist.getData().get(i).getJobId()){
	        			b=a;
	        		}
	        	 }
	        	
	        	if(b == 0){
	        		WorkingProgressAO wp=new WorkingProgressAO();
		        	wp.setJobId(Long.parseLong(workid));
		        	wp.setCurrentYear(year);
		        	wp.setStartDate(weekstart);
		        	wp.setEndDate(weekend);
		        	wp.setWeekNum(Integer.toString(week));
		        	wp.setPlanDeadline(nextFriday);
		        	workingProgressService.saveOrUpdate(wp);
	        		
	        	}
	        	
	         	
	           }else{
	        	
	        	
	        
	    
	           }

	        return "redirect:/pc/workingtable/list";
		   }
	   
	   
		
	}


	



